/*
 * @Description: Micro初始化
 * @Autor: HuiSir<github.com/huisir001>
 * @Date: 2022-07-15 16:35:27
 * @LastEditTime: 2022-07-22 17:24:50
 */
import type Koa from 'koa'
import Micro, { useConfig, log } from 'tcp-micro-service'

// 读取配置
const { server, registerServer } = useConfig()
const micro = new Micro(server.name)

export default async () => {
    // 连接注册中心
    // 先判断是否已连接
    if (!micro.hasSocket(registerServer.name)) {
        await new Promise((resolve, reject) => {
            micro.client(registerServer, (err) => {
                if (err) {
                    reject(new Error(`服务 ${registerServer.name} 连接失败：${err.message}`))
                    return
                }
                log.info(`已连接到 ${registerServer.name}(注册中心) 服务`)
                resolve(null)
            })
        })
    }

    // 判断是否连接到用户中心
    if (!micro.hasSocket('user')) {
        // 查询user服务数据
        const { ok, data, msg } = await micro.request({
            service: registerServer.name,
            path: `/find/user`,
            data: { method: 'SYS' }
        })

        if (ok === 1) {
            // 连接此服务
            await new Promise((resolve, reject) => {
                micro.client(data, (err) => {
                    if (err) {
                        reject(new Error(`服务 user 连接失败：${err.message}`))
                        return
                    }
                    log.info(`已连接到 user 服务`)
                    resolve(null)
                })
            })
        } else {
            throw new Error(msg)
        }
    }

    return micro
}